package org.ihelpuoo.parser;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Writer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.ihelpuoo.lang.LoaderException;
import org.ihelpuoo.lang.RenderException;
import org.ihelpuoo.xml.XMLWriter;
import org.w3c.dom.Document;

public abstract class AbstractXMLEngine extends AbstractTextEngine implements XMLParser, XMLRender
{

	@Deprecated
	public void parse(Reader r) throws LoaderException
	{
		throw new LoaderException("Can not support Reader as the param");
	}

	@Override
	public void parse(InputStream ins) throws LoaderException
	{
		try
		{
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = builder.parse(ins);
			this.valueOf(doc);
		}
		catch (Exception e)
		{
			throw LoaderException.wrap(e);
		}
	}

	public void render2(Writer w) throws RenderException
	{
		try
		{
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = builder.newDocument();
			if (w instanceof XMLWriter)
				((XMLWriter)w).write(doc);
			else
				XMLWriter.wrap(w).write(doc);
		}
		catch (ParserConfigurationException e)
		{
			throw new RenderException(e);
		}
		catch (IOException e)
		{
			throw new RenderException(e);
		}
	}

}
